const {userModel}=require("../mongodb")
const {success,fail}=require("../toast")

module.exports=function(router) {
    router.get("/user",async ctx=>{//查询
        try{
            const data=await userModel.find(ctx.request.body);
            return success(ctx,data);
        }catch(error){
            return fail(ctx,error);
        }
    })
    router.get("/user/:id", async ctx => {//动态路由
        try {
            const data = await userModel.findOne({_id:ctx.params.id});
            return success(ctx, data);
        } catch (error) {
            return fail(ctx, error);
        }
    })
    router.post("/user",async (ctx)=>{//添加
    try{
        const data=await userModel.create(ctx.request.body);
        return success(ctx,data);
    }catch(error){
        return fail(ctx,error);
    }
})

router.delete("/user",async (ctx)=>{//删除
    try{
        var _id=ctx.request.body._id;
            let data=[];
            if(_id instanceof Array){
                data= await userModel.deleteMany({_id:{$in:_id}});
            }else{
                data= await userModel.deleteOne({_id:_id});
            }
        return success(ctx,data);
    }catch(error){
        return fail(ctx,error);
    }
})

router.put("/user/:id",async (ctx)=>{//修改
    try{
        const data=await userModel.updateOne({_id:ctx.params.id},ctx.request.body);
        return success(ctx,data);
    }catch(error){
        return fail(ctx,error);
    }
})

}


